import * as api from '@/api/model'
import { approve } from '@/api/parse'

const state = {
  list: [],
  detail: null,
  manualList: [],
  manualDetail: null
}

const mutations = {
  SET_LIST: (state, list) => {
    state.list = list
  },
  SET_DETAIL: (state, detail) => {
    state.detail = detail
  },
  SET_MANUAL_LIST: (state, list) => {
    state.manualList = list
  },
  SET_MANUAL_DETAIL: (state, detail) => {
    state.manualDetail = detail
  }
}

const actions = {
  async fetchList({ commit }, payload) {
    const data = await api.getList(payload)
    const list = data && data.records || []
    commit('SET_LIST', list)
  },
  async fetchManualList({ commit }) {
    const data = await api.getList({ type: 0 })
    const list = data && data.records || []
    commit('SET_MANUAL_LIST', list)
  },
  async submit({ commit }, { excelId, name, type, data }) {
    const list = data && data.map(it => ({ ...it, edit: undefined })) || []
    return await api.save({ excelId, name, type }, list)
  },
  async approve(_, { modelId, fileName, data }) {
    return await approve({ modelId, fileName }, data)
  },
  async fetchDetail({ commit }, id) {
    const data = await api.getDetail(id)
    commit('SET_DETAIL', data)
  },
  async deleteModel({ dispatch }, id) {
    await api.delModel(id)
    dispatch('fetchList')
  },
  async tagValue({ commit, state }, { excelId, sheetName, axis }) {
    const { value } = await api.getTagValue({ excelId, sheetName, axis })
    const detail = state.detail
    const list = detail && detail.tags || []
    const idx = list.findIndex(it => (it.sheetName === sheetName || !it.sheetName) && it.axis === axis)
    if (idx >= 0) {
      list[idx].value = value
      commit('SET_DETAIL', { ...detail, tags: list })
    }
  },
  async tagTime({ commit, state }, { excelId, sheetName, axis, timeFormat }) {
    const data = await api.genTagsFormTimeFormat({ excelId, sheetName, axis, timeFormat })
    if (Array.isArray(data)) {
      const list = state.detail && state.detail.tags || []
      const tags = [...list, ...data]
      commit('SET_DETAIL', { ...state.detail, tags })
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
